/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-04-26 15:33:09
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-05 22:22:32
 * @FilePath: \src\src\LicenseManager.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "LicenseManager.h"
#include "common.h"
#include "CLogger.h"
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

extern LicenseManager LicenseManager::c_instance;

LicenseManager::LicenseManager(){
    strcpy(c_sn, "0000000000000000");
}

LicenseManager::~LicenseManager(){

}

std::string LicenseManager::getSHA512(std::string filename){

    if(filename.empty()){
        return "";
    }
    std::string lic_fname = LICENSE_FILE_PATH;
    lic_fname += "/"+filename+".lic";
    if (0 != access(lic_fname.c_str(), F_OK)){
        return "";
    }

    FILE *f= fopen(lic_fname.c_str(), "r");
    char buf[1024] = {0};

    if(NULL == f){
        return "";
    } else {
        if(NULL == fgets(buf, sizeof(buf), f)){
            memset(buf, 0, sizeof(buf));
        }
        char* find = strchr(buf, '\n');   //查找换行符
        if(find){                         //如果find不为空指针
            *find = '\0';                 //就把一个空字符放在这里
        }
    }
    return buf;
}


bool LicenseManager::IsLicensed(){
	while(true){
		get_dev_sn(c_sn, sizeof(c_sn));
		CLogger::getInstance()->log_i("device sn:%s", c_sn);
		SHA512 sha;
        std::string sn = c_sn;
        sn = "QCW_"+sn;
        std::string real_sha = sha.hash(sn);
        std::string lic_sha = getSHA512(c_sn);
		CLogger::getInstance()->log_i("device license:%s", lic_sha.c_str());
        if(0 == strcmp(real_sha.c_str(), lic_sha.c_str())){
            CLogger::getInstance()->log_i("license is valid");
            return true;
        }
		sleep(1);
	}
    return false;
}

LicenseManager* LicenseManager::GetInstance(){
    return &c_instance;
}
